import preferences from '@ohos.data.preferences';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';


class PreferencesUtil {
  preMap: Map<string, preferences.Preferences> = new Map()
  async loadPreference(content: common.Context, name: string,) {
    console.log('testtag', 'loadPreference')
    try {
      let pref = await preferences.getPreferences(content, name)
      this.preMap.set(name, pref)
    } catch (e) {
      console.log('testtag', `preferences[${name}]加载失败`, JSON.stringify(e))
    }
  }
  // 存储
  async putPreferenceValue(name: string, key: string, value: preferences.ValueType) {
    if(!this.preMap.has(name)) {
      console.log('testtag', `preferences[${name}]未初始化`)
      return
    }
    try {
      let pref = this.preMap.get(name)
      // 写入数据
      await pref?.put(key, value)
      // 刷盘
      await pref?.flush()
    } catch(e) {
      console.log('testtag', `preferences[${name}]保存失败`, JSON.stringify(e))
    }
  }
  // 读取
  async getPreferenceValue(
    name: string,
    key: string,
    defaultValue: preferences.ValueType
  ): Promise<preferences.ValueType> { // 明确声明返回类型
    if (!this.preMap.has(name)) {
      console.log('testtag', `preferences[${name}]未初始化`);
      return defaultValue; // 返回传入的默认值更合理
    }

    try {
      const pref = this.preMap.get(name);
      if (!pref) {
        console.log('testtag', `preferences[${name}]实例不存在`);
        return defaultValue;
      }

      return await pref.get(key, defaultValue);

    } catch (e) {
      console.log('testtag', `preferences[${name}]读取失败`, JSON.stringify(e));
      return defaultValue; // 异常时返回默认值
    }
  }
  // 删除
  async deletePreferenceValue(name: string, key: string,) {
    if(!this.preMap.has(name)) {
      console.log('testtag', `preferences[${name}]未初始化`)
      return
    }
    try {
      let pref = this.preMap.get(name)
      await pref?.delete(key)
    } catch(e) {
      console.log('testtag', `preferences[${name}]删除失败`, JSON.stringify(e))
    }
  }
  // 监听键值变化 (精确订阅数据变更，只有被订阅的key值发生变更后，在执行flush方法后，触发callback回调。)
  async onDataChange(name: string, keys: string[]) {
    if(!this.preMap.has(name)) {
      console.log('testtag', `preferences[${name}]未初始化`)
      return
    }
    try {
      let pref = this.preMap.get(name)
      // 写入数据
      let observer = (data: Record<string, preferences.ValueType>) => {
        for (const keyValue of Object.entries(data)) {
          console.info('testtag',`observer : ${keyValue}`)
        }
        console.info('testtag',"The observer called.")
      }
      pref?.on('dataChange', keys, observer);
    } catch(e) {
      console.log('testtag', `preferences[${name}]保存失败`, JSON.stringify(e))
    }
  }
}

const preferencesUtil = new PreferencesUtil()
export  default  preferencesUtil